<template>
  <div class="userview-content-box">
    <div class="mask" v-show="showMask" @click="showMask=false"></div>
    <div class="big-image"
         v-show="showMask"
         @click="showMask=false">
      <img :src="bigImageUrl" style="width:800px;minHeight:600px;borderRadius:20px" alt="">
    </div>
    <el-breadcrumb separator="/" class="page-title">
      <el-breadcrumb-item :to="{ path: 'shopUser' }">Users</el-breadcrumb-item>
      <el-breadcrumb-item>View</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="search-box container-padding">
      <el-form :inline="true" label-position="top" :model="submitForm" :rules="rules" size="mini" ref="submitForm"
               v-loading="loading" class="form-min-width">
        <div class="container-box label-style">
          <!--status-->
          <el-row>
            <el-form-item label="Status" prop="Status">
              <el-select style="width: 200px" v-model="submitForm.status" placeholder="" disabled>
                <el-option v-for="i in status" :key="i.value" :label="i.label" :value="i.value"></el-option>
              </el-select>
            </el-form-item>
          </el-row>
          <!--phone-->
          <el-row>
            <el-form-item style="width: 200px" label="Registration Phone" prop="account">
              <el-input v-model="submitForm.account" disabled></el-input>
            </el-form-item>
          </el-row>
          <!--facebookId-->
            <el-row>
              <el-form-item style="width: 200px" label="Facebook ID">
                <el-input v-model="facebookId" disabled></el-input>
              </el-form-item>
            </el-row>
            <el-row>
            <!--region-->
            <el-form-item label="Region" prop="regionId">
              <el-select style="width: 200px" v-model="submitForm.regionId" placeholder="" @change="getTownships"
                         disabled>
                <el-option v-for="rg in regions" :key="rg.value" :label="rg.text" :value="rg.value"></el-option>
              </el-select>
            </el-form-item>
            <!--township-->
            <el-form-item label="Township" prop="townshipId">
              <el-select style="width: 200px" v-model="submitForm.townshipId" placeholder="" disabled>
                <el-option v-for="ts in townshipData" :key="ts.value" :label="ts.text" :value="ts.value"></el-option>
              </el-select>
            </el-form-item>
          </el-row>
          <!--street-->
          <el-row>
            <el-form-item label="Street" style="width: 200px" prop="">
              <el-input v-model="submitForm.street" disabled></el-input>
            </el-form-item>
          </el-row>
          <!--photo-->
          <el-row>
            <el-form-item label="Photo" class="agent-photo" prop="">
              <span class="user-photo">
                <img :src="userPhoto"
                     style="width:77px;height:77px;borderRadius:5px"
                     v-if="userPhoto"
                     @click="showBigImage(userPhoto)"
                >
              </span>
            </el-form-item>
          </el-row>
          <!--user name-->
          <el-row>
            <el-form-item label="User name" style="width: 200px" prop="name">
              <el-input v-model="submitForm.name" disabled></el-input>
            </el-form-item>
            <div>Letter (a-z), number (0-9), underscore (_) only. 5-20 characters.</div>
          </el-row>
          <!--分割线-->
          <div class="line-separat"></div>
          <h3>ShopGoGo app</h3>
          <!--Display phone to buyer-->
          <el-form-item label="Display phone to buyer">
            <el-radio v-model="submitForm.displayPhone" label="1" disabled>NO</el-radio>
            <el-radio v-model="submitForm.displayPhone" label="2" disabled>YES</el-radio>
          </el-form-item>
          <!--Description-->
          <el-row>
            <el-form-item label="Description" prop="description">
              <el-input
                style="min-width:500px;"
                type="textarea"
                :rows="5"
                :maxlength="2000"
                placeholder=""
                v-model="submitForm.description" disabled>
              </el-input>
            </el-form-item>
          </el-row>
          <!--分割线-->
          <div class="line-separat"></div>
          <h3>BestProperty app</h3>
          <!--Advertisement phones-->
          <el-row>
            <el-form-item label="Advertisement phones (separated by comma)" style="width: 400px">
              <el-input v-model="submitForm.phone" disabled></el-input>
            </el-form-item>
          </el-row>
          <!--Advertisement Email-->
          <el-row>
            <el-form-item label="Advertisement Email" style="width: 400px">
              <el-input v-model="submitForm.email" disabled></el-input>
            </el-form-item>
          </el-row>
          <div class="line-separat"></div>
          <h3>Internal use</h3>
          <!--Seller category-->
          <el-row>
            <span class="label-title">Seller category</span>
            <div class="container-box">
              <el-form-item label="" class="label-vertical features-check">
                <el-checkbox-group
                  v-model="submitForm.categoryIds" disabled>
                  <el-checkbox v-for="i in sellerCategory" :label="i.value" :key="i.value">{{i.text}}</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </div>
          </el-row>
          <el-row>
            <el-form-item label="User's website" style="width: 400px" prop="street">
              <el-input v-model="submitForm.website" disabled></el-input>
            </el-form-item>
          </el-row>
          <!--facebook-->
          <el-row>
            <el-form-item label="User's facebook" style="width: 400px" prop="street">
              <el-input v-model="submitForm.facebook" disabled></el-input>
            </el-form-item>
          </el-row>
          <!--Notes (internal use)-->
          <el-row>
            <el-form-item label="Notes" prop="notes">
              <el-input
                style="min-width:500px;"
                type="textarea"
                :rows="5"
                :maxlength="2000"
                placeholder=""
                v-model="submitForm.notes" disabled>
              </el-input>
            </el-form-item>
          </el-row>
          <el-row>
            <el-checkbox v-model="submitForm.fromBackend" disabled>upload excel data from backend (electronics data)</el-checkbox>
          </el-row>
          <!--facebook messenger url-->
          <el-row>
            <el-form-item
              label="Facebook messenger url (example: http://m.me/username)"
              style="width: 400px"
            >
              <el-input v-model="submitForm.facebookMessengerUrl" disabled></el-input>
            </el-form-item>
          </el-row>
          <el-row :gutter="40" type="flex" justify="center" style="padding:40px 0;">
            <el-col :span="4">
              <el-button @click.native="cancelPutForm()" size="medium" type="info" style="width:100%">
                Cancel
              </el-button>
            </el-col>
            <el-col :span="4">
              <el-button @click.native="toNewAd"
                         v-loading.fullscreen.lock="fullscreenLoading" size="medium" type="success" style="width:100%">
                New ad
              </el-button>
            </el-col>
            <el-col :span="4">
              <el-button @click.native="toNewActivity"
                         v-loading.fullscreen.lock="fullscreenLoading" size="medium" type="success" style="width:100%">
                New activity
              </el-button>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <el-tabs type="border-card" @tab-click=selectTable>
        <el-tab-pane label="Activity"></el-tab-pane>
        <el-tab-pane label="User Update Log"></el-tab-pane>
      </el-tabs>
      <div class="list-items-box" v-show="ifShowActivity">
        <!--表格-->
        <el-table
          :data="activityTable"
          v-loading="tableLoading"
          border
          ref="singleTable"
          highlight-current-row
          @current-change="handleCurrentChange"
          style="width: 100%"
          :row-class-name="tableRowClassName"
        >
          <el-table-column
            prop="Property"
            label="View"
            align="center"
            width="100">
            <template slot-scope="scope">
              <el-button
                size="mini"
                @click="toPage(scope.row.id,'/viewCustomerActivity')">View
              </el-button>
            </template>
          </el-table-column>
          <el-table-column
            prop="Property"
            label="Edit"
            align="center"
            width="100">
            <template slot-scope="scope">
              <el-button
                size="mini"
                @click="toPage(scope.row.id,'/newCustomerActivity')">Edit
              </el-button>
            </template>
          </el-table-column>

          <!--Status-->
          <el-table-column
            prop="status"
            label="Status"
            align="center"
            min-width="100">
            <template slot-scope="scope">
              <p>{{getStatus(scope.row.status)}}</p>
            </template>
          </el-table-column>

          <!--Activity Date-->
          <el-table-column
            prop="activityTime"
            label="Activity Date"
            align="center"
            min-width="180">
            <template slot-scope="scope">
              <p>{{dateFormat(scope.row.activityTime)}}</p>
            </template>
          </el-table-column>

          <!--Activity Type-->
          <el-table-column
            prop="discount"
            label="Activity Type"
            align="center"
            min-width="120">
            <template slot-scope="scope">
              <p>{{getActivityType(scope.row.activityType)}}</p>
            </template>
          </el-table-column>

          <!--Objective-->
          <el-table-column
            prop="people"
            label="Objective"
            align="center"
            min-width="150">
            <template slot-scope="scope">
              <p>{{getObjective(scope.row.objectives, scope.row.otherObjective)}}</p>
            </template>
          </el-table-column>

          <!--Notes-->
          <el-table-column
            prop="content"
            label="Notes"
            align="center"
            min-width="120">
          </el-table-column>

          <!--Created Date-->
          <el-table-column
            prop="createTime"
            label="Created Date"
            align="center"
            min-width="180">
            <template slot-scope="scope">
              <p>{{dateFormat(scope.row.createTime)}}</p>
            </template>
          </el-table-column>

          <!--Created By-->
          <el-table-column
            prop="createBy"
            label="Created By"
            align="center"
            min-width="120">
          </el-table-column>

          <!--Updated Date-->
          <el-table-column
            prop="updateTime"
            label="Updated Date"
            align="center"
            min-width="180">
            <template slot-scope="scope">
              <p>{{dateFormat(scope.row.updateTime)}}</p>
            </template>
          </el-table-column>

          <!--Updated By-->
          <el-table-column
            prop="updateBy"
            label="Updated By"
            align="center"
            min-width="120">
          </el-table-column>

        </el-table>
        <!--分页-->
        <div class="block" style="margin-top: 15px;text-align: center;">
          <el-pagination
            @size-change="handleChangeSizeActivity"
            @current-change="handleChangePageActivity"
            :current-page="activityPageData.pageNum"
            :page-size="activityPageData.pageSize"
            :page-sizes="[10, 20, 50, 100, 500]"
            :page-count="activityPageInfo.totalPages"
            :total="activityPageInfo.totalCount"
            layout="total, prev, pager, next, jumper, sizes">
          </el-pagination>
        </div>
      </div>
      <div class="list-items-box" v-show="ifShowLog">
        <!--表格-->
        <el-table
          :data="logTable"
          v-loading="tableLoading"
          border
          style="width: 100%">
          <!--User Status-->
          <el-table-column
            prop=""
            label="User Status"
            align="center"
            min-width="100">
            <template slot-scope="scope">
              <p>{{getStatus(scope.row.status)}}</p>
            </template>
          </el-table-column>

          <!--Sql-->
          <el-table-column
            prop=""
            label="Sql"
            align="center"
            min-width="100">
            <template slot-scope="scope">
              <p>{{dateFormat(scope.row.activityTime, 'Date')}}</p>
            </template>
          </el-table-column>

          <!--Activity Type-->
          <el-table-column
            prop=""
            label="Updated Date"
            align="center"
            min-width="100">
            <template slot-scope="scope">
              <p>{{getActivityType(scope.row.activityType)}}</p>
            </template>
          </el-table-column>

          <!--Objective-->
          <el-table-column
            prop=""
            label="Updated By"
            align="center"
            min-width="100">
            <template slot-scope="scope">
              <p>{{getObjective(scope.row.objectives, scope.row.otherObjectives)}}</p>
            </template>
          </el-table-column>
        </el-table>
        <!--分页-->
        <div class="block" style="margin-top: 15px;text-align: center;">
          <el-pagination
            @size-change="handleChangeSizeLog"
            @current-change="handleChangePageLog"
            :current-page="logPageData.pageNum"
            :page-size="logPageData.pageSize"
            :page-sizes="[10, 20, 50, 100, 500]"
            :page-count="logPageInfo.totalPages"
            :total="logPageInfo.totalCount"
            layout="total, prev, pager, next, jumper, sizes">
          </el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
  import qs from 'qs'
  //引入本地文件
  import regions from '@/json/region'
  import townships from '@/json/township'
  import sellerCategory from '@/json/sellerCategory'
  import {shopUserDetail, getActivityList} from '../../api/guc_api.js'

  export default {
    name: 'newRestaurant',
    data() {
      return {
        //用户id
        id: '',
        facebookId:'',
        //用户头像链接
        userPhoto: '',
        //status数据
        status: [
          {
            label: 'Active',
            value: '1'
          },
          {
            label: 'Not interested',
            value: '0'
          },
          {
            label: 'Stoped business',
            value: '3'
          },
          {
            label: 'Called but no answer',
            value: '5'
          },
          {
            label: 'Wrong phone number',
            value: '6'
          },
          {
            label: 'Suspended',
            value: '4'
          },
          {
            label: 'Deleted',
            value: '2'
          },
        ],
        //直接引用的本地数据
        regions,
        townships,
        sellerCategory,
        //遍历生成的本地数据
        townshipData: [],
        submitForm: {
          // 表单数据必填字段
          status: '',
          name: '',
          regionId: '',
          townshipId: '',
          street: null,
          facebook: '',
          account: '',
          phone: '',
          email: '',
          notes: '',
          description: '',
          displayPhone: '',
          website: '',
          categoryIds: [],
          fromBackend:'',
          facebookMessengerUrl:''
        },
        // 添加表单修改数据和字段
        fullscreenLoading: false,
        loading: false,
        //总共有四处需要验证
        rules: {
          name: [
            {
              validator: (rule, value, callback) => {
                if (value === '') {
                  callback(new Error('please enter user name'));
                } else if (/^[a-z0-9_]{0,20}$/.test(value) == false) {
                  callback(new Error('wrong format'));
                } else {
                  callback();
                }
              }, trigger: 'blur'
            }
          ],
          account: [
            {required: true, message: 'please enter your phone number', trigger: 'blur'}
          ],
          regionId: [
            {required: true, message: 'please select  region', trigger: 'change'}
          ],
          townshipId: [
            {required: true, message: 'please select  township', trigger: 'change'}
          ],
        },
        //表示是新建还是登录状态
        //添加表格数据
        activityTable: [],
        logTable: [],
        ifShowActivity: true,
        ifShowLog: false,
        tableLoading: false,
        // activity分页
        activityPageData: {
          pageNum: 1,
          pageSize: 10,
        },
        activityPageInfo: {
          totalCount: 0,
          totalPages: 0
        },
        // 当前行
        currentRow: null,
        // log分页
        logPageData: {
          pageNum: 1,
          pageSize: 10,
        },
        logPageInfo: {
          totalCount: 0,
          totalPages: 0
        },
        //大图预览
        showMask:false,
        bigImageUrl:'',
      }
    },
    methods: {
      // 显示大图
      showBigImage(url){
        this.showMask=true
        this.bigImageUrl=url
      },
      //用来控制单双行样式
      tableRowClassName({row, rowIndex}) {
        if (rowIndex % 2 === 1) {
          return 'odd-row';
        }
        else if (rowIndex % 2 === 0) {
          return 'even-row';
        }
        return '';
      },
      handleCurrentChange(val) {
        this.currentRow = val;
      },
      getTownships() {
        this.submitForm.townshipId = ''
        let townData = []
        this.townships.forEach((item) => {
          if (item.regionId === this.submitForm.regionId) {
            townData.push(item)
          }
        })
        this.townshipData = townData
      },
      // message alert 用于前端错误提示信息
      messageToastErr(msg) {
        this.$message({
          showClose: true,
          message: msg,
          duration: 5000,
          type: 'error'
        })
      },
      // 编辑时获取用户id后初始化表单
      initForm() {
        this.loading = true
        let params = {
          userId: this.id
        }
        shopUserDetail(params).then((res) => {
          if (res.data) {
            this.loading = false
            let obj = res.data
            this.submitForm.status = obj.status + ''
            this.submitForm.name = this.$translateLang(obj.name||'','unicodeTozawgyi')||'';
            this.submitForm.regionId = obj.regionId
            this.getTownships()
            this.submitForm.townshipId = obj.townshipId
            this.submitForm.street = this.$translateLang(obj.street||'','unicodeTozawgyi')||'';
            this.submitForm.facebook = obj.facebook
            this.submitForm.account = obj.account
            this.submitForm.phone = obj.phone
            this.submitForm.email = obj.email
            this.submitForm.notes = this.$translateLang(obj.notes||'','unicodeTozawgyi')||'';
            this.submitForm.description = this.$translateLang(obj.description||'','unicodeTozawgyi')||''
            this.submitForm.displayPhone = obj.displayPhone + ''
            this.submitForm.website = obj.website
            this.facebookId=obj.facebookId
            this.submitForm.fromBackend=(obj.fixedUser==1)?true:false
            this.submitForm.facebookMessengerUrl=obj.facebookMessengerUrl
            let userCategoryArr = []
            obj.userCategory.forEach((item) => {
              userCategoryArr.push(item.id)
            })
            this.submitForm.categoryIds = userCategoryArr || []
            // 用户头像初始化
            this.userPhoto = obj.photo
          }
        }).catch((error) => {
          this.loading = false
          if (error.response) {
            this.messageToastErr(error.response)
          }
          else {
            this.messageToastErr('Newwork Error')
          }
        })
      },
      cancelPutForm() {
          this.$router.go(-1)
      },
      //view和edit页面的跳转
      toPage(id, route) {
        this.$router.push({
          path: route,
          query: {
            id: id,
            landlordId: this.id
          }
        })
      },
      //去新增ad页面
      toNewAd(){
        this.$router.push({
          path: '/shopAdNew',
          query: {
            userId: this.id
          }
        })
      },
      //跳转到新建activity页面
      toNewActivity() {
        this.$router.push({
          path: '/newCustomerActivity',
          query: {
            landlordId: this.id
          }
        })
      },
      //activity分页和获取数据的方法的方法
      handleChangeSizeActivity(val) {
        this.activityPageData.pageSize = parseInt(val)
        this.activityPageData.pageNum = 1
        this.getActivityList()
      },
      handleChangePageActivity(val) {
        this.activityPageData.pageNum = val
        this.getActivityList()
      },
      getActivityList(pageNum) {
        this.tableLoading = true;
        if (pageNum === 1) {
          this.activityPageData.pageNum = 1;
        }
        let searchForm = {
          landlordId: this.id || '',
          sort: 'create_time desc'
        };
        getActivityList(Object.assign(searchForm, this.activityPageData)).then((res) => {
          this.activityTable = res.data.object.list || []
          // 分页信息配置
          this.activityPageInfo.totalPages = res.data.object.pages
          this.activityPageInfo.totalCount = res.data.object.total
          this.tableLoading = false;
        }).catch((e) => {
          console.log(e)
          this.tableLoading = false;
        })
      },
      //log分页和获取数据的方法
      handleChangeSizeLog(val) {
        this.logPageData.pageSize = parseInt(val)
        this.logPageData.pageNum = 1
        this.getActivityList()
      },
      handleChangePageLog(val) {
        this.pageData.pageNum = val
        this.getActivityList()
      },
      getLogList(pageNum) {
        this.tableLoading = true;
        if (pageNum == 1) {
          this.logPageData.pageNum = 1;
        }
        let searchForm = {
          landlordId: this.id || '',
          sort: 'create_time desc'
        };
        // qs.stringify(searchForm)
        getActivityList(Object.assign(searchForm, this.logPageData)).then((res) => {
          this.logTable = res.data.object.list || []
          // 分页信息配置
          this.logPageInfo.totalPages = res.data.object.pages
          this.logPageInfo.totalCount = res.data.object.total
          this.tableLoading = false;
        }).catch((e) => {
          console.log(e)
          this.tableLoading = false;
        })
      },
      //tab选择展示表格的方法
      selectTable(tab) {
        // console.log(tab)
        if (tab.index === "0") {
          // console.log('显示第一个表格')
          this.showActivity()
        }
        if (tab.index === "1") {
          // console.log('显示第二个表格')
          this.showLog()
        }
      },
      showActivity() {
        this.ifShowActivity = true
        this.ifShowLog = false
        this.getActivityList()
      },
      showLog() {
        this.ifShowActivity = false
        this.ifShowLog = true
        this.getLogList()
      },
      //activity表格数据处理方法
      getStatus(value) {
        if (value === 1) {
          return 'Active';
        } else if (value === 2) {
          return 'Deleted';
        }
      },
      dateFormat(value) {
        let date = new Date(value)
        let Y = date.getFullYear()
        let m = date.getMonth() + 1
        let d = date.getDate()
        let H = date.getHours()
        let i = date.getMinutes()
        let s = date.getSeconds()
        if (m < 10) {
          m = '0' + m
        }
        if (d < 10) {
          d = '0' + d
        }
        if (H < 10) {
          H = '0' + H
        }
        if (i < 10) {
          i = '0' + i
        }
        if (s < 10) {
          s = '0' + s
        }
        let t = Y + '-' + m + '-' + d + '  ' + H + ':' + i + ':' + s
        return t
      },
      getActivityType(value) {
        if (value == 1) {
          return 'Call'
        } else if (value == 2) {
          return 'Visit'
        } else if (value == 3) {
          return 'Received call'
        }
      },
      getObjective(objective, other) {
        if (objective) {
          let arr = objective.split(",");
          let str = '';
          for (let i = 0; i < arr.length; i++) {
            switch (Number(arr[i])) {
              case 1:
                str += 'Introduction, ';
                break;
              case 2:
                str += 'Make appointmen, ';
                break;
              case 3:
                str += 'Software installation, ';
                break;
              case 4:
                str += 'Training, ';
                break;
              case 5:
                str += 'Software Troubleshooting, ';
                break;
              case 6:
                str += 'Complaint, ';
                break;
              case 7:
                str += 'Others:' + other + ', ';
                break;
              case 8:
                str += 'Data update, ';
                break;
            }
          }

          str = str.substring(0, str.lastIndexOf(','))

          return str;
        }
      },
    },
    mounted() {
      window.scrollTo(0,0)
      this.id = this.$route.query.id || ''
      this.initForm()
      this.getActivityList()
    }
  }
</script>
<style scoped>
  .line-separat {
    border-bottom: 1px solid #e6e6e6;
    margin: 10px 0;
  }
</style>
<style>
  .page-title {
    padding: 20px 40px;
    border-bottom: 1px solid #e6e6e6;
    font-size: 20px;
  }

  .userview-content-box{
    position:relative;
  }

  .userview-content-box .container-padding {
    padding: 20px 40px 0 40px;
  }

  .label-title {
    display: block;
    line-height: 28px;
    padding: 0 0 10px 0;
    font-size: 14px;
    color: #606266;
  }

  .label-vertical .el-form-item__label {
    width: 100%;
  }

  .features-check .el-checkbox {
    width: 20%;
  }

  .features-check .el-checkbox + .el-checkbox {
    margin-left: 0;
  }

  .features-check.el-form-item {
    display: block !important;
  }

  .bottom-line {
    border-bottom: 1px solid #e6e6e6;
  }

  .margin-line {
    margin: 10px 0;
  }

  .list-info {
    text-align: center;
    display: block;
  }
  .user-photo{
    width: 79px;
    height: 79px;
    display:inline-block;
    border:dotted 1px black;
    border-radius:5px;
    box-sizing:border-box;
  }
  /*显示大图的样式*/
  .mask{
    position: absolute;
    z-index: 2100;
    background-color: rgba(33,33,33,.2);
    margin: 0;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    -webkit-transition: opacity .3s;
    transition: opacity .3s;
  }
  .big-image{
    position:absolute;
    left:50%;
    top:500px;
    transform:translate(-50%,-50%);
    width: 800px;
    height: 600px;
    z-index:2200;
  }
</style>
